package com.ruoyi.system.service.impl.fxImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.fx.FxToJoin;
import com.ruoyi.system.domain.fx.FxUser;
import com.ruoyi.system.mapper.fx.FxToJoinMapper;
import com.ruoyi.system.service.fx.IFxToJoinService;
import com.ruoyi.system.service.fx.IFxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

/**
 * 加盟Service业务层处理
 *
 * @author ruoyi
 * @date 2024-08-19
 */
@Service
public class FxToJoinServiceImpl extends ServiceImpl<FxToJoinMapper, FxToJoin> implements IFxToJoinService {
    @Autowired
    private FxToJoinMapper fxToJoinMapper;

    @Autowired
    private IFxUserService fxUserService;

    /**
     * 查询加盟
     *
     * @param id 加盟主键
     * @return 加盟
     */
    @Override
    public FxToJoin selectFxToJoinById(Long id) {
        return fxToJoinMapper.selectFxToJoinById(id);
    }

    /**
     * 查询加盟列表
     *
     * @param fxToJoin 加盟
     * @return 加盟
     */
    @Override
    public List<FxToJoin> selectFxToJoinList(FxToJoin fxToJoin) {
        List<Long> role = SecurityUtils.getLoginUser().getUser().getRoles()
                .stream().map(SysRole::getRoleId).collect(Collectors.toList());
        if (role.contains(1L) || role.contains(6L)) {
            return fxToJoinMapper.selectFxToJoinList(fxToJoin);
        }
        Long userId = SecurityUtils.getUserId();
        FxUser fxUser = fxUserService.selectFxUserByUserId(userId);
            List<FxToJoin> join = new ArrayList<>();
        if (StringUtils.isNotNull(fxUser)) {
            join.add(fxToJoinMapper.selectFxToJoinById(fxUser.getParentAccountId()));
        }
        return join;
    }

    /**
     * 查询供应商列表（下拉框使用）
     * @return
     */
    @Override
    public List<FxToJoin> getSupplierList() {
        FxToJoin fxToJoin = new FxToJoin();
        fxToJoin.setRoleType(3);
        fxToJoin.setStatus(1);
        fxToJoin.setDelFlag(0);
        fxToJoin.setIsAbleUse(1L);
        List<Long> roles = SecurityUtils.getLoginUser().getUser().getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList());
        FxUser fxUser = fxUserService.selectFxUserByUserId(SecurityUtils.getUserId());
        List<FxToJoin> toJoinList = fxToJoinMapper.selectFxToJoinList(fxToJoin);
        if (roles.contains(3L) && StringUtils.isNotNull(fxUser)) {
            return toJoinList.stream().filter(j -> Objects.equals(j.getId(), fxUser.getParentAccountId())).collect(Collectors.toList());
        }
        return toJoinList;
    }

    /**
     * 新增加盟 (小程序加盟 3供应商，4店铺)
     *
     * @param fxToJoin 加盟
     * @return 结果
     */
    @Override
    public int insertFxToJoin(FxToJoin fxToJoin) {
        if (!this.checkPhoneUnique(fxToJoin.getPhone())) {
            throw new GlobalException("该手机号已提交过申请");
        }
        String id = System.currentTimeMillis() + "" + ThreadLocalRandom.current().nextInt(100, 1000);
        fxToJoin.setId(Convert.toLong(id));
        fxToJoin.setCreateTime(DateUtils.getNowDate());
        fxToJoin.setApplyId(SecurityUtils.getUserId());
        return fxToJoinMapper.insertFxToJoin(fxToJoin);
    }

    /**
     * 查询
     * @return
     */
    @Override
    public FxToJoin selectToJoin(Integer type) {
        Long userId = SecurityUtils.getUserId();
        List<Long> roles = SecurityUtils.getLoginUser().getUser().getRoles()
                .stream().map(SysRole::getRoleId).collect(Collectors.toList());
        FxToJoin fxToJoin = new FxToJoin();
        fxToJoin.setApplyId(userId);
        fxToJoin.setRoleType(type);
        if (roles.contains(4L) || roles.contains(3L)) {
            FxUser fxUser = fxUserService.selectFxUserByUserId(userId);
            if (type == 3L) {
                return Optional.ofNullable(fxToJoinMapper.selectFxToJoinById(fxUser.getParentAccountId())).orElse(new FxToJoin());
            }else {
                fxToJoin.setStoreId(fxUser.getStoreId());
            }
        }
        List<FxToJoin> list = fxToJoinMapper.selectFxToJoinList(fxToJoin);
        if (StringUtils.isNotEmpty(list)) {
            return list.get(0);
        }
        return new FxToJoin();
    }

    /**
     * 修改加盟
     *
     * @param fxToJoin 加盟
     * @return 结果
     */
    @Override
    public int updateFxToJoin(FxToJoin fxToJoin) {
        FxToJoin toJoin = fxToJoinMapper.selectFxToJoinById(fxToJoin.getId());
        if (StringUtils.isNull(toJoin)) {
            throw new GlobalException("信息有误");
        }
        if (StringUtils.isNotNull(toJoin.getStatus()) && toJoin.getStatus() == 2) {
            fxToJoin.setStatus(0);
        }
        return fxToJoinMapper.updateFxToJoin(fxToJoin);
    }

    /**
     * 批量删除加盟
     *
     * @param ids 需要删除的加盟主键
     * @return 结果
     */
    @Override
    public int deleteFxToJoinByIds(Long[] ids) {
//        return fxToJoinMapper.deleteFxToJoinByIds(ids);
        return fxToJoinMapper.updateDelFlag(ids);
    }

    /**
     * 删除加盟信息
     *
     * @param id 加盟主键
     * @return 结果
     */
    @Override
    public int deleteFxToJoinById(Long id) {
        return fxToJoinMapper.deleteFxToJoinById(id);
    }

    /**
     * 校验加盟手机号 是否唯一
     * @param phone
     * @return
     */
    @Override
    public boolean checkPhoneUnique(String phone) {
        List<Integer> list = new ArrayList<>();
        list.add(0);
        list.add(1);
        LambdaQueryWrapper<FxToJoin> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(FxToJoin::getId)
                .eq(FxToJoin::getPhone, phone).in(FxToJoin::getStatus, list);
        FxToJoin info = fxToJoinMapper.selectOne(wrapper);
        if (StringUtils.isNotNull(info))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public int updateFxToJoinWithEasy(FxToJoin fxToJoin){
        FxToJoin toJoin = fxToJoinMapper.selectFxToJoinById(fxToJoin.getId());
        toJoin.setStatus(fxToJoin.getStatus());
        if (StringUtils.isNotNull(fxToJoin.getStatus()) && fxToJoin.getStatus() == 1L) {
            fxUserService.insertUserToJoin(toJoin);
            Long userId = fxUserService.getSysUserId(toJoin.getPhone());
            FxUser fxUser = fxUserService.selectFxUserByUserId(userId);
            toJoin.setSysuserId(userId);
            toJoin.setStoreId(fxUser.getStoreId());
        }
        return fxToJoinMapper.updateFxToJoin(toJoin);
//        return  fxToJoinMapper.updateFxToJoin(fxToJoin);
    }
}
